package SVN::TeamTools::Index::FullQueryParser;
use base qw( Lucy::Search::QueryParser );
use Lucy::Search::TermQuery;
use Lucy::Search::PhraseQuery;
use Lucy::Search::ORQuery;
use SVN::TeamTools::Index::PrefixQuery;
use Carp;

sub _tokenize {
	my ( $self, $query_string ) = @_;
	my @tokens;
	while ( length $query_string ) {
		if ( $query_string =~ s/^\s+// ) {
			next;	# skip whitespace
		}
		elsif ( $query_string =~ s/^("[^"]*(?:"|$))// ) {
			push @tokens, $1;	# double-quoted phrase
		}
		else {
			$query_string =~ s/(\S+)//;
			push @tokens, $1;	# single word
		}
	}
	return \@tokens;
}

#sub parse {
#	my ( $self, $query_string ) = @_;
#	my $tokens = $self->_tokenize($query_string);
#	my $or_query = Lucy::Search::ORQuery->new;
#	for my $token (@$tokens) {
#		my $leaf_query = Lucy::Search::LeafQuery->new( text => $token );
#		$or_query->add_child($leaf_query);
#	}
#	return $self->expand($or_query);
#}

sub expand_leaf {
	my ( $self, $leaf_query ) = @_;
	my $text = $leaf_query->get_text;
	if ( $text =~ /\*$/ ) {
		my $or_query = Lucy::Search::ORQuery->new;
		for my $field ( @{ $self->get_fields } ) {
			my $prefix_query = SVN::TeamTools::Index::PrefixQuery->new(
				field	=> $field,
				prefix	=> $text,
			);
			$or_query->add_child($prefix_query);
		}
		return $or_query;
	}
	else {
		return $self->SUPER::expand_leaf($leaf_query);
	}
}
1;
